package logic

import (
	"context"
	"encoding/json"
	"good_srv/cache"
	"good_srv/good"
	"good_srv/internal/svc"
	"good_srv/models"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodListLogic {
	return &GoodListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品列表
func (l *GoodListLogic) GoodList(in *good.GoodListRequest) (*good.GoodListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	var goods []models.Good
	var goodslist []*good.GoodList

	query := models.DB.
		Offset(int(offset)).Limit(int(pageSize))
	if in.Stoc == "price" {
		models.DB.Where("price desc").Find(&goods)
	} else if in.Stoc == "stock" {
		models.DB.Where("stock desc").Find(&goods)
	}

	query = query.Find(&goods)
	result, _ := cache.Rdb.Get(l.ctx, "good_show").Result()
	if result != "" {
		for _, m := range goods {
			list := good.GoodList{
				Title:  m.Title,
				Price:  float32(m.Price),
				Stock:  m.Stock,
				Status: m.Status,
			}
			goodslist = append(goodslist, &list)
			json.Unmarshal([]byte(result), &goods)
		}
	} else {
		marshal, _ := json.Marshal(&goods)
		cache.Rdb.Set(l.ctx, "good_show", marshal, time.Minute*5)
	}
	return &good.GoodListResponse{
		List: goodslist,
	}, nil
}
